<script setup lang="ts" name="ComponentPickerBlock">
import { LexicalTypeaheadMenuPlugin, MenuOption, useBasicTypeaheadTriggerMatch, useLexicalComposer } from 'lexical-vue'
import {
  flip,
  offset,
  shift,
  useFloating,
} from '@floating-ui/vue'
import type {
  TextNode,
} from 'lexical'
import {
  $getSelection,
  $isRangeSelection,
} from 'lexical'
import { mergeRegister } from '@lexical/utils'
import { computed, onMounted, ref } from 'vue'
import { $createCustomTextNode } from '../custom-text/node'
import { INSERT_VARIABLE_BLOCK_COMMAND,INSERT_VARIABLE_VALUE_BLOCK_COMMAND } from '../variable-block/common'
import {CLEAR_HIDE_MENU_TIMEOUT} from '../types'
import { INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND } from '../types'

class PickerBlockMenuOption extends MenuOption {
  group?: string
  constructor(
     data: {
      key: string
      group?: string
      onSelect?: () => void
    },
  ) {
    super(data.key)
    this.group = data.group
  }
}

const floatingRef = ref<any>();



function getStyles(refenceRef:any) {
  const { floatingStyles, isPositioned } = useFloating(refenceRef,floatingRef,{
    placement: 'bottom-start',
    middleware: [
      offset(0), // fix hide cursor
      shift({
        padding: 8,
      }),
      flip(),
    ],
  })
  console.log(floatingStyles.value,isPositioned.value)
  return {...floatingStyles.value,visibility: isPositioned.value ? 'visible' : 'hidden'}
}

const editor = useLexicalComposer()
const queryString = ref<string | null>(null)


const checkForTriggerMatch = useBasicTypeaheadTriggerMatch('{', {
  minLength: 0,
})

const options = ref<Array<PickerBlockMenuOption>>([
    new PickerBlockMenuOption({key:'username','group':'a'}),
    new PickerBlockMenuOption({key:'age','group':'a'}),
    new PickerBlockMenuOption({key:'sex','group':'b'}),
])

function onSelectOption({
  option: selectedOption,
  textNodeContainingQuery: nodeToRemove,
  closeMenu,
}: {
  option: PickerBlockMenuOption
  textNodeContainingQuery: TextNode | null
  closeMenu: () => void
  matchingString: string
}) {
  editor.update(() => {
    const selection = $getSelection()
    if (!$isRangeSelection(selection) || selectedOption == null)
      return

    if (nodeToRemove && selectedOption?.key)
        nodeToRemove.remove()
   
    editor.dispatchCommand(INSERT_WORKFLOW_VARIABLE_BLOCK_COMMAND, {varName:selectedOption.key,group:selectedOption.group})
    closeMenu()
  })
}
</script>

<template>
  <LexicalTypeaheadMenuPlugin
    v-slot="{anchorElementRef, listItemProps: { selectedIndex, setHighlightedIndex, selectOptionAndCleanUp } }"
    :trigger-fn="checkForTriggerMatch"
    :options="options"
    @query-change="queryString = $event"
    @select-option="onSelectOption"
  >     
      <Teleport :disabled="anchorElementRef == null || options.length === 0" :to="anchorElementRef">
              <div 
                class='w-[260px]  var-picker-panel '
              >
               <template v-for="(option,index) in options">
                <div v-if="index !==0 && options[index-1].group != options[index].group" class='var-picker-panel-divider'></div>
                <div   :tabIndex="-1"
                    class="var-picker-panel-var hover:bg-state-base-hover"
                    @mouseenter="setHighlightedIndex(index)"
                    @click="setHighlightedIndex(index); selectOptionAndCleanUp(option)"
                    @keyup.enter="setHighlightedIndex(index); selectOptionAndCleanUp(option)" 
                    >
                    <div class='ml-1 text-[13px] text-text-secondary  hover:text-sky-700'>{{option.key}}</div>
                </div>
               </template>
               
              </div>
        </Teleport>
  </LexicalTypeaheadMenuPlugin>
</template>

<style lang="css" scoped>
.var-picker-panel {
    --tw-shadow: 0px 4px 6px -2px rgba(16, 24, 40, 0.03), 0px 12px 16px -4px rgba(16, 24, 40, 0.08);
    --tw-shadow-colored: 0px 4px 6px -2px var(--tw-shadow-color), 0px 12px 16px -4px var(--tw-shadow-color);
    box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
    padding: 0.25rem ;
    border-radius: 0.5rem;
    border-width: 0.5px;
}

.var-picker-panel-var {
    display: flex;
    height: 1.5rem;
    cursor: pointer;
    align-items: center;
    border-radius: 0.375rem;
    padding-left: 0.75rem ;
    padding-right: 0.75rem ;
 
} 
.var-picker-panel-var:hover{
    background-color: #c8ceda33;
}

.var-picker-panel-divider {
    margin-top: 0.25rem /* 4px */;
    margin-bottom: 0.25rem /* 4px */;
    height: 1px;
    width: 100%;
    --tw-translate-x: -0.25rem /* -4px */;
    transform: translate(var(--tw-translate-x), var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y));
    background-color: #1018280a;
}
</style>

